package ynu.edu.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import ynu.edu.dto.LoginRequest;
import ynu.edu.dto.RegisterRequest;
import ynu.edu.dto.ResponseResult;
import ynu.edu.dto.UserResponse;
import ynu.edu.service.UserService;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 用户控制器
 */
@RestController
@RequestMapping({"/user", "/", "/api/user"})  // 添加对/api/user前缀的支持
@CrossOrigin // 添加跨域支持
public class UserController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 用户登录
     * @param loginRequest 登录请求体
     * @return 登录结果
     */
    @PostMapping("/login")
    public ResponseResult<UserResponse> login(@RequestBody LoginRequest loginRequest) {
        try {
            System.out.println("\n====== 收到登录请求 ======");
            System.out.println("请求参数: userId=" + loginRequest.getUserId() + ", password=******");
            
            // 直接调用服务
            UserResponse userResponse = userService.login(loginRequest);
            System.out.println("登录成功: " + userResponse.getUserName());
            return ResponseResult.success(userResponse);
        } catch (Exception e) {
            System.err.println("登录异常: " + e.getClass().getName() + ": " + e.getMessage());
            e.printStackTrace();
            return ResponseResult.error("登录失败: " + e.getMessage());
        }
    }
    
    /**
     * 用户注册
     * @param request 注册请求
     * @return 注册结果
     */
    @PostMapping("/register")
    public ResponseResult<UserResponse> register(@RequestBody RegisterRequest request) {
        try {
            System.out.println("\n====== 收到注册请求 ======");
            System.out.println("注册信息: userId=" + request.getUserId() + ", userName=" + request.getUserName());
            
            UserResponse userResponse = userService.register(request);
            System.out.println("注册成功: " + userResponse.getUserName());
            return ResponseResult.success(userResponse);
        } catch (Exception e) {
            System.err.println("注册异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseResult.error("注册失败: " + e.getMessage());
        }
    }
    
    /**
     * 获取用户信息
     * @param userId 用户ID
     * @return 用户信息
     */
    @GetMapping("/getById/{userId}")
    public ResponseResult<UserResponse> getUserInfo(@PathVariable String userId) {
        try {
            System.out.println("\n====== 收到获取用户信息请求 ======");
            System.out.println("用户ID: " + userId);
            
            UserResponse userResponse = userService.getUserById(userId);
            System.out.println("获取用户信息成功: " + userResponse.getUserName());
            return ResponseResult.success(userResponse);
        } catch (Exception e) {
            System.err.println("获取用户信息异常: " + e.getMessage());
            e.printStackTrace();
            return ResponseResult.error("获取用户信息失败: " + e.getMessage());
        }
    }
} 